'use client';

import './index.scss';
import Breadbar from '@/components/Breadbar';
import { useActions, useClientParams, useGlobalState } from '@/hooks';
import {
  getCheckMySku,
  getProductDetail,
  postAddMySku,
  postArrivalNotice,
} from '@/services';
import { useEffect, useRef, useState } from 'react';
import CustomCarousel from './components/CustomCarousel';
import { showLoading } from '@/components/ContentLoading';
import { formatCurrency, sleep } from '@/utils/common';
import DeliveryList from './components/DeliveryList';
import StockStatus from './components/StockStatus';
import { showToast } from '@/components/Toast';
import PostcodeQuery from './components/PostcodeQuery';
import StyleSelector from './components/StyleSelector';
import NotFound from '@/app/not-found';
import CopyButton from '@/components/CopyButton';
import GoTopButton from '@/components/GoTopButton';
import ToolTips from '@/components/ToolTips';
import DescriptionBox from './components/DescriptionBox';

type pageProps = {
  params: {
    slug?: string[];
    searchParams?: Obj;
  };
  categories: any[];
  paths: string[];
  searchParams: Obj<any>;
  pageTitle?: string;
  category?: Obj<any> | null;
  product?: Obj<any>;
  filters?: Obj<any>;
};

const Product = (props: pageProps) => {
  const {
    params,
    paths,
    searchParams,
    categories,
    category,
    product,
    pageTitle,
  } = props;
  // console.log(
  //   params,
  //   paths,
  //   searchParams,
  //   categories?.length,
  //   category,
  //   // product,
  //   pageTitle
  // );
  const {
    basePath,
    // pathname,
    // queryObject,
    catePaths,
    // searchParams,
    // paramsObject,
    // categoryObject,
    // filterObject,
    router,
  } = useClientParams();

  const [skuInfo, setSkuInfo] = useState<Obj | null>(null);
  const [productPath, setProductPath] = useState<any[]>([]);
  const [discountOff, setDiscountOff] = useState<any>('');
  const [inCompare, setInCompare] = useState(false);
  const [onMySkuList, setOnMySkuList] = useState(false);
  const { compareList } = useGlobalState('product');
  const { userInfo } = useGlobalState('user');
  const { addCompareList, restoreCompareList } = useActions();
  const [skuNotfound, setSkuNotfound] = useState(false);
  const [hasNotify, setHasNotify] = useState(false);

  //============================================================================

  const querySkuInfo = async () => {
    const hideLoading = showLoading({
      inner: false,
      mask: true,
      maskStyle: { backgroundColor: 'rgba(255,255,255,.05)' },
    });
    const queryParams = { skus: paths.join('%2F') };
    const sku =
      (await getProductDetail(queryParams).catch(e => {
        void e;
      })) || null;
    hideLoading();
    if (sku) {
      setSkuInfo(sku);
    } else {
      setSkuNotfound(true);
    }
  };
  const querySkuInfoRef = useRef(querySkuInfo);
  querySkuInfoRef.current = querySkuInfo;

  useEffect(() => {
    querySkuInfoRef.current();
  }, [catePaths]);

  //============================================================================

  const initProduct = (sku: Obj) => {
    // setSkuInfo(sku);
    const ph = [];
    sku.l1_category_name && ph.push(sku.l1_category_name);
    sku.l2_category_name && ph.push(sku.l2_category_name);
    sku.l3_category_name && ph.push(sku.l3_category_name);
    ph.push(sku.title);
    setProductPath(ph);
    const disc = sku?.special_price
      ? Number((100 * (sku.price - sku.special_price)) / sku.price).toFixed(0)
      : '';
    setDiscountOff(disc);
    const in_compare = !!compareList?.map(p => p.sku)?.includes(sku.sku);
    setInCompare(in_compare);
    checkIsInMySku(sku.sku);
    setHasNotify(!!sku.stock_notify);
  };
  const initProductRef = useRef(initProduct);
  initProductRef.current = initProduct;

  useEffect(() => {
    compareList && skuInfo && initProductRef.current(skuInfo);
  }, [compareList, skuInfo]);

  //============================================================================

  const initCompareList = () => {
    const userKey = btoa(userInfo?.email || '');
    restoreCompareList(userKey);
  };
  const initCompareListRef = useRef(initCompareList);
  initCompareListRef.current = initCompareList;
  useEffect(() => {
    initCompareListRef.current();
  }, []);

  const checkIsInMySku = async (sku: string) => {
    const res = await getCheckMySku({ skus: sku }).catch(e => {
      void e;
    });
    const isInMySku = res?.[0]?.isInMySkuList;
    setOnMySkuList(!!isInMySku);
  };
  //============================================================================

  const handleAddToCompare = (e: any) => {
    if (!skuInfo) return;
    const cData = {
      title: skuInfo.title,
      sku: skuInfo.sku,
      image: skuInfo.gallery?.at(0),
      entity_id: skuInfo.entity_id,
    };
    addCompareList(cData);
  };
  const handleAddToMySku = async (e: any) => {
    if (skuInfo?.sku) {
      const hideLoading = showLoading({
        inner: false,
        mask: true,
        maskStyle: { backgroundColor: 'rgba(255,255,255,.05)' },
      });
      const res = await postAddMySku({ skus: skuInfo?.sku }).catch(e => {
        void e;
      });
      if (res) {
        showToast({
          type: res.success ? 'success' : 'error',
          message: res?.message,
          duration: 2000,
        });
        res.success && setOnMySkuList(true);
      }
      hideLoading();
    }
  };
  const handleAddAllToMySku = async (e: any) => {
    if (skuInfo?.sku) {
      const hideLoading = showLoading({
        inner: false,
        mask: true,
        maskStyle: { backgroundColor: 'rgba(255,255,255,.05)' },
      });
      const res = await postAddMySku({
        parent_id: skuInfo?.parent_id,
      }).catch(e => {
        void e;
      });
      if (res) {
        showToast({
          type: res.success ? 'success' : 'error',
          message: res?.message,
          duration: 2000,
        });
        res.success && setOnMySkuList(true);
      }
      hideLoading();
    }
  };
  const handleLinkToBulkBuy = (e: any) => {
    router.push('https://web.my-company.net.cn/bulk-order');
  };
  const handleNotifyMe = async () => {
    const hideLoading = showLoading();
    const res = await postArrivalNotice({
      product_id: skuInfo?.entity_id,
    }).catch(e => {
      void e;
    });
    if (res) {
      setHasNotify(true);
      showToast({
        type: res.success ? 'success' : 'error',
        message: res.message,
        duration: 2000,
      });
    }
    hideLoading();
  };

  return (
    <div className="main">
      {skuNotfound && <NotFound />}
      {skuInfo ? (
        <div className="main-wrapper">
          <Breadbar paths={productPath} basePath={basePath} crossPage={true} />
          <div className="content-product-wrapper">
            <div className="content-infos">
              <div className="content-infos-mobile-title">
                <h1 className="content-infos-product-title">
                  {skuInfo?.title}
                </h1>
              </div>
              <div className="content-infos-gallery">
                <CustomCarousel imgList={skuInfo?.gallery || []} />
              </div>
              <div className="content-infos-parameter">
                <div className="content-infos-row content-infos-pc-title">
                  <h1 className="content-infos-product-title">
                    {skuInfo?.title}
                  </h1>
                </div>
                <div className="content-infos-row">
                  <h2 className="content-infos-product-sku">
                    Supplier SKU:{' '}
                    <span className="content-infos-product-sku-text">
                      {skuInfo?.sku}
                      <CopyButton copyText={skuInfo?.sku} />
                    </span>
                  </h2>
                  <div className="content-infos-product-stock">
                    <StockStatus
                      in_stock={skuInfo?.stock_qty > 0}
                      stock_qty={skuInfo?.stock_qty}
                      status={skuInfo?.status}
                    />
                  </div>
                </div>
                <div className="content-infos-row content-infos-row-baseline">
                  <div className="content-infos-product-price">
                    {skuInfo?.special_price ? (
                      <>
                        {formatCurrency(skuInfo.special_price)}
                        <span className="price-discount">
                          {discountOff}% off
                        </span>
                      </>
                    ) : (
                      <>{formatCurrency(skuInfo?.price)}</>
                    )}
                  </div>
                  {skuInfo?.special_price && (
                    <div className="content-infos-product-regular">
                      Regular: {formatCurrency(skuInfo?.price)}
                    </div>
                  )}
                  {skuInfo?.RrpPrice && (
                    <div className="content-infos-product-rrp">
                      RRP: {formatCurrency(skuInfo?.RrpPrice)}
                    </div>
                  )}
                </div>

                {Number(skuInfo?.stock_qty) <= 0 && (
                  <div className="content-infos-row">
                    {hasNotify ? (
                      <div className="content-infos-notify-me-already">
                        We will notify you when the item is available
                      </div>
                    ) : (
                      <button
                        className="content-infos-notify-me-button"
                        onClick={handleNotifyMe}
                      >
                        NOTIFY ME WHEN AVAILABLE
                      </button>
                    )}
                  </div>
                )}

                <StyleSelector skuInfo={skuInfo} />

                <DeliveryList zoneRates={skuInfo?.zone_rates} />
                <div className="content-infos-product-buttons">
                  {!inCompare ? (
                    compareList?.length >= 4 ? (
                      <button
                        className="content-infos-product-button full-compare"
                        disabled={true}
                      >
                        Compare List is full
                      </button>
                    ) : (
                      <button
                        className="content-infos-product-button"
                        onClick={handleAddToCompare}
                      >
                        Add to Compare
                      </button>
                    )
                  ) : (
                    <button
                      className="content-infos-product-button added-compare"
                      disabled={true}
                    >
                      {/* <span className="iconfont icon-check-fill"></span> */}
                      In Compare List
                    </button>
                  )}

                  {onMySkuList ? (
                    <span className="content-infos-product-placeholder">
                      On My Sku List
                    </span>
                  ) : (
                    <button
                      className="content-infos-product-button"
                      onClick={handleAddToMySku}
                    >
                      Add to My Sku List
                    </button>
                  )}

                  <button
                    className="content-infos-product-button"
                    onClick={handleLinkToBulkBuy}
                  >
                    <ToolTips
                      text={
                        'Please contact us if you are interested on bulk buying this product'
                      }
                      style={{
                        width: '180px',
                        fontSize: '14px',
                        whiteSpace: 'break-spaces',
                      }}
                    >
                      Bulk Buy
                    </ToolTips>
                  </button>
                  {skuInfo?.default_sku_id > 0 &&
                    skuInfo?.variants?.length > 0 && (
                      <button
                        className="content-infos-product-button"
                        onClick={handleAddAllToMySku}
                      >
                        Add All To My Sku List
                      </button>
                    )}
                </div>

                <PostcodeQuery skuInfo={skuInfo} />
              </div>
            </div>
            <div className="content-description">
              <div className="content-description-title">Description</div>
              <div className="content-description-wrapper">
                <DescriptionBox description={skuInfo?.desc || ''} />
              </div>
            </div>
          </div>
        </div>
      ) : (
        ''
      )}

      <GoTopButton />
    </div>
  );
};

export default Product;
